package com.example.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 *
 * https://artisan.blog.csdn.net/article/details/113829208
 *
 * 默认的序列化
 *
 * RedisTemplate使用的是 JdkSerializationRedisSerializer
 * StringRedisTemplate使用的是 StringRedisSerializer
 *
 * JSON 字符串占用变大，所以实际项目中，我们很少采用 Jackson2JsonRedisSerializer
 *
 * org.springframework.data.redis.serializer.OxmSerializer
 * 使用 Spring OXM 实现将对象和 String 的转换，从而 String 和二进制数组的转换。 没见过哪个项目用过
 *
 * @author luowj12
 * @since 2021/5/25 15:06
 */
@Configuration
public class RedisTemplateConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 缓存redis-redisTemplate
     *
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //TODO:指定大key序列化策略为为String序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        //JSON 字符串占用变大，所以实际项目中，我们很少采用 Jackson2JsonRedisSerializer
        //redisTemplate.setValueSerializer(RedisSerializer.json());
        //TODO:指定hashKey序列化策略为String序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    /**
     * 缓存redis-stringRedisTemplate
     *
     * @return
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        //采用默认配置即可-后续有自定义配置时则在此处添加即可
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        return stringRedisTemplate;
    }
}
